<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\manager\notify\gateway;

use app\common\model\AssistantOrder;
use app\common\model\Order;
use app\common\model\PayLog;
use app\common\model\UserAccount;
use app\common\model\UserCoupon;
use think\Db;
use think\Exception;

class Assistant
{

    public function dealWith($response,$isTrans=true)
    {
        if ($isTrans)
            Db::startTrans();
        try {

            $response = json_decode(json_encode($response),true);
            if (!$orderInfo = Order::where('order',$response['out_trade_no'])->find()){
                throw new Exception('当前记录不存在');
            }

            if ($orderInfo['pay_state'] != Order::PAY_STATE_INIT){
                throw new Exception('当前订单已处理');
            }


            $extend_param = [];
            if ($orderInfo['extend_param']){
                $extend_param = unserialize($orderInfo['extend_param']);
            }
            if ($response['result_code'] == 'SUCCESS') {

                if(!Order::update([
                    'trilateral_pay_order'=>$response['transaction_id'],
                    'pay_date'=>strtotime($response['time_end']),
                    'up_date'=>time(),
                    'pay_state'=>Order::PAY_STATE_SUCCESS
                ],['po_id'=>$orderInfo['po_id']])){
                    throw new Exception('订单更新失败');
                }

                if(!PayLog::update(['processed'=>PayLog::PROCESSED_STATUS_YES,'update_time'=>time()],['order'=>$response['out_trade_no']])){
                    file_put_contents('callback.log','订单日志更新失败',FILE_APPEND);
                    throw new Exception('订单日志更新失败');
                }

                if (!UserAccount::where(['user_id'=>$orderInfo['user_id']])->update([
                    'consumed_money'=>Db::raw('consumed_money + '.$orderInfo['real_money']),
                    'assistant_count'=>Db::raw('assistant_count + 1'),
                    'version'=>Db::raw('version + 1'),
                    'updatetime'=>time()
                ])) {
                    throw new Exception('账户消费金额累加失败');
                }

                if ($orderInfo['assistant_ids']){

                    if(!\app\common\model\assistant\Order::where('order_id',$orderInfo['po_id'])->update(['pay_status'=>\app\common\model\assistant\Order::PAY_STATUS_YES,'update_time'=>time()])){
                        throw new Exception('助教订单状态修改失败');
                    }

                    if(!AssistantOrder::where('order_id',$orderInfo['po_id'])->update(['pay_status'=>AssistantOrder::PAY_STATUS_YES,'update_time'=>time()])){
                        throw new Exception('用户助教订单状态修改失败');
                    }
                }

                if ($orderInfo['user_coupon_id'] && $orderInfo['pref_money'] > 0){

                    if (!UserCoupon::where('id', $orderInfo['user_coupon_id'])->update(['block' => UserCoupon::BLOCK_NO,'status'=>UserCoupon::STATUS_USED,'update_time'=>time()])){
                        throw new Exception('优惠券使用失败，请稍后再试');
                    }
                }

            }

            if ($isTrans)
                Db::commit();
            return ['code'=>1,'message'=>'success'];
        }catch (Exception $exception){
            if ($isTrans)
                Db::rollback();
            return ['code'=>0,'message'=>$exception->getMessage()];
        }
    }
}